package com.atguigu.vod.controller;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.aliyuncs.vod.model.v20170321.DeleteVideoResponse;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import com.atguigu.commonutils.Result;
import com.atguigu.servicebase.exception.GuliException;
import com.atguigu.vod.service.VodService;
import com.atguigu.vod.utils.ConstantUtils;
import com.atguigu.vod.utils.InitObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.ws.rs.Path;
import java.util.List;

@RestController
@RequestMapping("/eduvod/video")
@Slf4j
public class VodController {

    @Autowired
    private VodService vodService;

    //上传视频到阿里云接口
    @PostMapping("/uploadAlyVideo")
    public Result uploadAliyun(MultipartFile file) {
        //返回上传视频的id值
        String videoId =  vodService.uploadVideoAly(file);
        return Result.ok().data("videoId",videoId);
    }

    //根据视频id删除阿里云视频
    @DeleteMapping("removeVideo/{id}")
    public Result remove(@PathVariable String id) {
        try {
            //初始化对象
            DefaultAcsClient client = InitObject.initVodClient(ConstantUtils.ACCESS_KEY_ID, ConstantUtils.ACCESS_KEY_SECRET);
            //创建删除视频的request对象
            DeleteVideoRequest request = new DeleteVideoRequest();
            //向request设置视频id
            request.setVideoIds(id);
            //调用初始化对象的方法实现删除视频功能
            client.getAcsResponse(request);
            log.info("删除的视频id: => {}",id);
            return Result.ok();
        } catch (Exception e) {
            e.printStackTrace();
            throw new GuliException(201,"删除视频失败");
        }
    }

    //删除多个阿里云视频的接口
    @DeleteMapping("/delete-batch")
    public Result deleteBatch(@RequestParam("videoIdList") List<String> videoIdList) {
        vodService.removeMoreAlyVideo(videoIdList);
        return Result.ok();
    }

    //根据视频id获取视频的凭证
    @GetMapping("/getPlayAuth/{id}")
    public Result getAuth(@PathVariable String id) {

        try {
            //创建初始化对象
            DefaultAcsClient client = InitObject.initVodClient(ConstantUtils.ACCESS_KEY_ID, ConstantUtils.ACCESS_KEY_SECRET);

            GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
            request.setVideoId(id);

            GetVideoPlayAuthResponse response = client.getAcsResponse(request);
            String playAuth = response.getPlayAuth(); //获取播放视频的凭证
            return Result.ok().data("playAuth",playAuth);
        } catch (Exception e) {
            e.printStackTrace();
            throw new GuliException(201,"获取视频失败");
        }
    }
}










